
const { GitProcess } = require('dugite')
const { FileUtils } = require('./Utils')

class GitRepo {
  constructor(repoPath, options) {
    console.log('GitRepo', repoPath, options);
    this.repoPath = repoPath;
    let defaultOptions = {
      silent: true,
    }
    for (let key in options) {
      defaultOptions[key] = options[key];
    }
    this.options = defaultOptions;    
  }

  async gitCommandHandler({command, options, success, failed}) {
    console.log("\n============> git command start <============");
    console.log(`$ git ${command.join(" ")}`);
    const result = await GitProcess.exec(command, this.repoPath, options);
    if (result.exitCode === 0) {
      console.log(result.stdout);
      console.log("===========> git command success <===========\n");
      if (success) {
        success(result.stdout);
      }
    } else {
      console.log(result.stderr);
      console.log("===========> git command failed  <===========\n");
      if (failed) {
        failed(result.stderr);
      } else {
        throw new Error(`execute 'git ${command.join(" ")}' failed`);
      }      
    }
  }

  async init() {
    if (!FileUtils.exists(this.repoPath)) {
      FileUtils.createDir(this.repoPath);
      await this.gitCommandHandler({
        command: ['init'],
      });
      return;
    }

    await this.gitCommandHandler({
      command: ['rev-parse', '--is-inside-work-tree'],
    });
  }

  async status() {
    await this.gitCommandHandler({
      command: ['status'],
    });
  }

  async add(files) {
    let args = files ? files : ["--all"];
    await this.gitCommandHandler({
      command: ['add', ...args],
    });
  }
  
  async commit(message) {
    message = message ? message : `commit files at ${new Date().toLocaleString()}`;
    await this.gitCommandHandler({
      command: ['commit', '-m', message],
    });
  }
}

if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
  // CommonJS 模块导出
  module.exports = {
    GitRepo
  };
} else if (typeof define === 'function' && define.amd) {
  // ES6 模块导出
  define([], GitRepo);
} else if (typeof exports === 'object') {
  // Node/CommonJS
  module.exports = {
    GitRepo
  };
} else {
  // Exported as a string, for Closure Compiler in advanced mode.
  var globalVar = (function() { return this; })();
  globalVar.GitRepo = GitRepo;
}